package com.toycloud.system.service.impl.business;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.toycloud.business.dto.params.business.FeedbackCompareParams;
import com.toycloud.business.dto.params.business.FeedbackProductParamManagerParams;
import com.toycloud.business.dto.results.CommonResult;
import com.toycloud.common.core.utils.DateUtils;
import com.toycloud.common.core.utils.StringUtils;
import com.toycloud.common.core.utils.uuid.IdUtils;
import com.toycloud.common.core.web.domain.AjaxResult;
import com.toycloud.system.domain.business.*;
import com.toycloud.system.mapper.business.FeedbackProductParamManagerDetailMapper;
import com.toycloud.system.mapper.business.FeedbackProductParamManagerMapper;
import com.toycloud.system.mapper.business.FeedbackProductParamScoreMapper;
import com.toycloud.system.mapper.business.FeedbackProductVersionManagerMapper;
import com.toycloud.system.service.business.IFeedbackProductParamManagerService;
import com.toycloud.system.utils.ExcelDealUtil;
import com.toycloud.system.utils.FileUrlUtils;
import com.toycloud.system.utils.Openstorage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * 产品参数管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-18
 */
@Slf4j
@Service
public class FeedbackProductParamManagerServiceImpl implements IFeedbackProductParamManagerService {
    @Resource
    private FeedbackProductParamManagerMapper feedbackProductParamManagerMapper;
    @Resource
    private FeedbackProductParamScoreMapper feedbackProductParamScoreMapper;
    @Resource
    private FeedbackProductParamManagerDetailMapper feedbackProductParamManagerDetailMapper;
    @Resource
    private FeedbackProductVersionManagerMapper feedbackProductVersionManagerMapper;
    @Autowired
    private Openstorage openstorage;

    /**
     * 查询产品参数管理
     *
     * @param id 产品参数管理主键
     * @return 产品参数管理
     */
    @Override
    public FeedbackProductParamManager selectFeedbackProductParamManagerById(String id) {
        FeedbackProductParamManager feedbackProductParamManager = feedbackProductParamManagerMapper.selectFeedbackProductParamManagerById(id);
        List<FeedbackProductParamManagerDetail> feedbackProductParamManagerDetail = feedbackProductParamManagerDetailMapper.listParent(id);
        List<OptionVO> brandlist = feedbackProductVersionManagerMapper.selectProductBrandOption();//产品品牌
        List<OptionVO> typelist = feedbackProductVersionManagerMapper.selectProductTypeOption();//产品品类
        List<OptionVO> modellist = feedbackProductVersionManagerMapper.selectProductModelOption();//产品型号
        feedbackProductParamManager.setProductbrandname(brandlist.stream().filter(item1 -> item1.getId().equals(feedbackProductParamManager.getProductbrandid())).findFirst().get().getName());
        feedbackProductParamManager.setProducttypename(typelist.stream().filter(item1 -> item1.getId().equals(feedbackProductParamManager.getProducttypeid())).findFirst().get().getName());
        feedbackProductParamManager.setProductmodelname(modellist.stream().filter(item1 -> item1.getId().equals(feedbackProductParamManager.getProductmodelid())).findFirst().get().getName());
        Map<String, Object> map = this.tableParam();
        ObjectMapper objectMapper = new ObjectMapper();
        String firstTab = map.get("first").toString();
        map.remove("first");

        feedbackProductParamManagerDetail.stream().forEach(item -> {
            map.forEach((key, value) -> {
                List<FeedbackProductParamManagerDetail> list = objectMapper.convertValue(value,
                        new TypeReference<List<FeedbackProductParamManagerDetail>>() {
                        });
                list.forEach(item1 -> {
                    if (item1.getParamid().equals(item.getParamid())) {
                        item1.setScore(item.getScore());
                        item1.setDetaildescription(item.getDetaildescription());
                        item1.setFileurl(item.getFileurl());
                    }
                });
                map.put(key, list);
            });
        });
        List<FeedbackProductParamManagerDetail> firstList = objectMapper.convertValue(map.get(firstTab),
                new TypeReference<List<FeedbackProductParamManagerDetail>>() {
                });
        feedbackProductParamManager.setScore(calculateWeightedScore(firstList));
        feedbackProductParamManager.setParameters(map);
        return feedbackProductParamManager;
    }

    public static String calculateWeightedScore(List<FeedbackProductParamManagerDetail> list) {
        double scoreSum = 0.0;
        double weightSum = 0.0;

        for (FeedbackProductParamManagerDetail entity : list) {
            Double score = parseToDouble(entity.getScore());
            Double weight = entity.getWeight();

            // 如果score或weight为null，则跳过该条目
            if (score == null || weight == null) {
                continue;
            }

            scoreSum += score;
            // 只有当score不为0时才累加weight
            if (score != 0) {
                weightSum += weight;
            }
        }

        // 计算并返回结果，如果权重总和为0，则返回0避免除以0错误
        return String.valueOf(weightSum != 0 ? Math.round((scoreSum / weightSum) * 10) / 10.0 : 0.0);
    }
    private static Double parseToDouble(String value) {
        try {
            return value != null && !value.isEmpty() ? Double.parseDouble(value) : null;
        } catch (NumberFormatException e) {
            return null; // 返回null表示转换失败
        }
    }

    /**
     * 查询产品参数管理列表
     *
     * @param feedbackProductParamManagerParams 产品参数管理
     * @return 产品参数管理
     */
    @Override
    public CommonResult<List<FeedbackProductParamManager>> selectFeedbackProductParamManagerList(FeedbackProductParamManagerParams feedbackProductParamManagerParams) {
        PageHelper.startPage(feedbackProductParamManagerParams.getCurrent(), feedbackProductParamManagerParams.getPageSize());
        if (StringUtils.isNotEmpty(feedbackProductParamManagerParams.getProductbrandid())) {
            feedbackProductParamManagerParams.setProductbrandids(Arrays.stream(feedbackProductParamManagerParams.getProductbrandid().split(",")).collect(Collectors.toList()));
        }
        if (StringUtils.isNotEmpty(feedbackProductParamManagerParams.getProducttypeid())) {
            feedbackProductParamManagerParams.setProducttypeids(Arrays.stream(feedbackProductParamManagerParams.getProducttypeid().split(",")).collect(Collectors.toList()));
        }
        if (StringUtils.isNotEmpty(feedbackProductParamManagerParams.getProductmodelid())) {
            feedbackProductParamManagerParams.setProductmodelids(Arrays.stream(feedbackProductParamManagerParams.getProductmodelid().split(",")).collect(Collectors.toList()));
        }
        List<FeedbackProductParamManager> feedbackProductParamManagers = feedbackProductParamManagerMapper.selectFeedbackProductParamManagerList(feedbackProductParamManagerParams);
        List<OptionVO> brandlist = feedbackProductVersionManagerMapper.selectProductBrandOption();//产品品牌
        List<OptionVO> typelist = feedbackProductVersionManagerMapper.selectProductTypeOption();//产品品类
        List<OptionVO> modellist = feedbackProductVersionManagerMapper.selectProductModelOption();//产品型号
        List<FeedbackProductParamScore> feedbackProductParamScores = feedbackProductParamScoreMapper.selectFeedbackProductParamScoreList();

        feedbackProductParamManagers.stream().forEach(item -> {
            item.setProductbrandname(brandlist.stream().filter(item1 -> item1.getId().equals(item.getProductbrandid())).findFirst().get().getName());
            item.setProducttypename(typelist.stream().filter(item1 -> item1.getId().equals(item.getProducttypeid())).findFirst().get().getName());
            item.setProductmodelname(modellist.stream().filter(item1 -> item1.getId().equals(item.getProductmodelid())).findFirst().get().getName());
            item.setScoreList(feedbackProductParamScores.stream()
                    .filter(item2 -> item2.getParentid().equals(item.getId()))
                    .peek(item2 -> {
                        double score = Double.parseDouble(item2.getScore());
                        DecimalFormat df = new DecimalFormat(score == 0 ? "0" : "#.0");
                        String formattedScore = df.format(score);
                        item2.setScore(formattedScore);
                    })
                    .collect(Collectors.toList()));

        });

        Page<FeedbackProductParamManager> FeedbackProductParamManagersPage = (Page<FeedbackProductParamManager>) feedbackProductParamManagers;
        return CommonResult.Success((int) FeedbackProductParamManagersPage.getTotal(), feedbackProductParamManagers);
    }

    /**
     * 新增产品参数管理
     *
     * @param feedbackProductParamManager 产品参数管理
     * @return 结果
     */
    @Override
    public AjaxResult insertFeedbackProductParamManager(FeedbackProductParamManager feedbackProductParamManager) throws Exception {


        feedbackProductParamManager.setCreateTime(DateUtils.getNowDate());
        //循环拿出key
        Map<String, Object> parameters = feedbackProductParamManager.getParameters();
        //校验数据
        ObjectMapper objectMapper = new ObjectMapper();
        parameters.remove("first");
        AtomicBoolean errorFlag = new AtomicBoolean(false);
        parameters.forEach((key, value) -> {
            List<FeedbackProductParamManagerDetail> list = objectMapper.convertValue(value,
                    new TypeReference<List<FeedbackProductParamManagerDetail>>() {
                    });
            list.stream().forEach(item -> {
                if (StringUtils.isNotEmpty(item.getScore())) {
                    if (Double.valueOf(item.getScore()) > 5) {
                        errorFlag.set(true);
                    }
                }
            });
        });
        if (errorFlag.get()) {
            //抛出异常
            throw new Exception("存在评分大于5的数据");
        }
        String id = IdUtils.simpleUUID();
        feedbackProductParamManager.setId(id);
        feedbackProductParamManagerMapper.insertFeedbackProductParamManager(feedbackProductParamManager);
        List<FeedbackProductParamManagerDetail> feedbackProductParamManagerDetails = feedbackProductParamManagerMapper.tableParam();
        List<OptionVO> optionVOS = feedbackProductParamManagerMapper.tableTitle();
        parameters.forEach((key, value) -> {
            String typeid = optionVOS.stream().filter(item1 -> item1.getName().equals(key)).findFirst().get().getId();
            List<FeedbackProductParamManagerDetail> list = objectMapper.convertValue(value,
                    new TypeReference<List<FeedbackProductParamManagerDetail>>() {
                    });
            double[] scoreall = {0.0};
            double[] listCount = {0.0};
            list.stream().forEach(item -> {
                if (StringUtils.isEmpty(item.getParamid())) {
                    item.setParamid(feedbackProductParamManagerDetails.stream().filter(item1 -> item1.getParamname().equals(item.getParamname())).findFirst().get().getId());
                }
                double score = Double.parseDouble(StringUtils.isEmpty(item.getScore()) ? "0" : item.getScore());
                scoreall[0] += score * item.getWeight();
                if (score != 0) {
                    listCount[0] = listCount[0] + item.getWeight();
                }
                item.setParentid(id);
                item.setType(key);
                item.setTypeid(typeid);
                item.setScore(StringUtils.isEmpty(item.getScore()) ? "" : item.getScore());
                item.setCreateTime(DateUtils.getNowDate());
                feedbackProductParamManagerDetailMapper.insertFeedbackProductParamManagerDetail(item);


            });
            if (list.size() != 0) {
                double finalScoreall = 0.0;
                if (listCount[0] != 0) {
                    finalScoreall = scoreall[0] / listCount[0];
                    finalScoreall = Math.round(finalScoreall * 10) / 10.0;
                }

                String configid = list.get(0).getTypeid();
                FeedbackProductParamScore feedbackProductParamScore = new FeedbackProductParamScore(null, id, finalScoreall + "", configid, key);
                feedbackProductParamScoreMapper.insertFeedbackProductParamScore(feedbackProductParamScore);
            }
        });

        return AjaxResult.success();
    }

    /**
     * 修改产品参数管理
     *
     * @param feedbackProductParamManager 产品参数管理
     * @return 结果
     */
    @Override
    public AjaxResult updateFeedbackProductParamManager(FeedbackProductParamManager feedbackProductParamManager) {
        feedbackProductParamManager.setUpdateTime(DateUtils.getNowDate());
        String id = feedbackProductParamManager.getId();
        feedbackProductParamManagerMapper.updateFeedbackProductParamManager(feedbackProductParamManager);
        List<FeedbackProductParamManagerDetail> feedbackProductParamManagerDetails = feedbackProductParamManagerMapper.tableParam();
        ObjectMapper objectMapper = new ObjectMapper();
        List<OptionVO> optionVOS = feedbackProductParamManagerMapper.tableTitle();
        AtomicBoolean errorFlag = new AtomicBoolean(false);
        //循环拿出key
        Map<String, Object> parameters = feedbackProductParamManager.getParameters();
        parameters.forEach((key, value) -> {
            String typeid = optionVOS.stream().filter(item1 -> item1.getName().equals(key)).findFirst().get().getId();
            List<FeedbackProductParamManagerDetail> list = objectMapper.convertValue(value,
                    new TypeReference<List<FeedbackProductParamManagerDetail>>() {
                    });
            double[] scoreall = {0.0};
            double[] listCount = {0.0};
            list.stream().forEach(item -> {
                if (StringUtils.isNotEmpty(item.getScore())) {
                    if (Double.valueOf(item.getScore()) > 5) {
                        errorFlag.set(true);
                    }
                }

                if (StringUtils.isEmpty(item.getParamid())) {
                    item.setParamid(feedbackProductParamManagerDetails.stream().filter(item1 -> item1.getParamname().equals(item.getParamname())).findFirst().get().getId());
                }

                double score = Double.parseDouble(StringUtils.isEmpty(item.getScore()) ? "0" : item.getScore());
                scoreall[0] += score * item.getWeight();
                if (score != 0) {
                    listCount[0] = listCount[0] + item.getWeight();
                }

                item.setParentid(id);
                item.setType(key);
                item.setTypeid(typeid);
                item.setScore(StringUtils.isEmpty(item.getScore()) ? "" : item.getScore());
                feedbackProductParamManagerDetailMapper.updateFeedbackProductParamManagerDetailByParentId(item);


            });
            if (list.size() != 0) {
                double finalScoreall = 0.0;
                if (listCount[0] != 0) {
                    finalScoreall = scoreall[0] / listCount[0];
                    finalScoreall = Math.round(finalScoreall * 10) / 10.0;
                }
                String configid = list.get(0).getTypeid();
                FeedbackProductParamScore feedbackProductParamScore = new FeedbackProductParamScore(null, id, finalScoreall + "", configid, key);
                feedbackProductParamScoreMapper.updateFeedbackProductParamScoreByparentId(feedbackProductParamScore);
            }
        });
        if (errorFlag.get()) {
            return AjaxResult.error("存在评分大于5的数据");
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除产品参数管理
     *
     * @param ids 需要删除的产品参数管理主键
     * @return 结果
     */
    @Override
    public int deleteFeedbackProductParamManagerByIds(Long[] ids) {
        return feedbackProductParamManagerMapper.deleteFeedbackProductParamManagerByIds(ids);
    }

    /**
     * 删除产品参数管理信息
     *
     * @param id 产品参数管理主键
     * @return 结果
     */
    @Override
    public int deleteFeedbackProductParamManagerById(String id) {
        return feedbackProductParamManagerMapper.deleteFeedbackProductParamManagerById(id);
    }

    @Override
    public Map<String, Object> tableParam() {
        List<FeedbackProductParamManagerDetail> list = feedbackProductParamManagerMapper.tableParam();
        List<OptionVO> optionVOS = feedbackProductParamManagerMapper.tableTitle();
        Map<String, Object> map = new HashMap<>();
        optionVOS.forEach(item -> {
            map.put(item.getName(), list.stream().filter(item1 -> item1.getParentid().equals(item.getId())).collect(Collectors.toList()));
        });
        map.put("first",optionVOS.get(0).getName());
        return map;
    }


    @Override
    public CommonResult<String> export2(FeedbackProductParamManagerParams params) {
        final String BASE_DIRECTORY = System.getProperty("user.dir");

        final String EXPORT_EXCEL_PATH = BASE_DIRECTORY + File.separator + "excel" + File.separator + "export" + File.separator;

        List<String> feedback_statistics_export_head = new ArrayList<>(Arrays.asList(
                "产品品牌",
                "产品品类",
                "产品型号",
                "产品版本",
                "创建时间"
        ));
        List<String> feedback_book_content_export_feild = new ArrayList<>(Arrays.asList(new String[]{
                "productbrandname", "producttypename", "productmodelname", "modelversion", "createTime"}));


        List<FeedbackProductParamManagerExport> feedbackProductParamManagers = feedbackProductParamManagerMapper.listExport(params);
        List<OptionVO> brandlist = feedbackProductVersionManagerMapper.selectProductBrandOption();//产品品牌
        List<OptionVO> typelist = feedbackProductVersionManagerMapper.selectProductTypeOption();//产品品类
        List<OptionVO> modellist = feedbackProductVersionManagerMapper.selectProductModelOption();//产品型号
        List<FeedbackProductParamScore> feedbackProductParamScores = feedbackProductParamScoreMapper.selectFeedbackProductParamScoreList();
        feedbackProductParamManagers.stream().forEach(item -> {
            item.setProductbrandname(brandlist.stream().filter(item1 -> item1.getId().equals(item.getProductbrandid())).findFirst().get().getName());
            item.setProducttypename(typelist.stream().filter(item1 -> item1.getId().equals(item.getProducttypeid())).findFirst().get().getName());
            item.setProductmodelname(modellist.stream().filter(item1 -> item1.getId().equals(item.getProductmodelid())).findFirst().get().getName());
            item.setScoreList(feedbackProductParamScores.stream().filter(item1 -> item1.getParentid().equals(item.getId())).collect(Collectors.toList()));
            try {
                setDynamicScores(item, item.getScoreList());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        });
        int a = 0;
        for (int i = 0; i < feedbackProductParamScores.size(); i++) {
            //如果feedback_statistics_export_head不存在feedbackProductParamScores.get(i).getConfigname()就add
            if (!feedback_statistics_export_head.contains(feedbackProductParamScores.get(i).getConfigname())) {
                feedback_statistics_export_head.add(feedbackProductParamScores.get(i).getConfigname());
                feedback_book_content_export_feild.add("score" + a);
                a++;
            }
        }
        //生成excel
        String excelPath = null;
        try {
            excelPath = ExcelDealUtil.exportObjectToExcel(feedback_statistics_export_head, feedback_book_content_export_feild, feedbackProductParamManagers, EXPORT_EXCEL_PATH);
        } catch (Exception e) {
            e.getMessage();
        }
        //上传至云存储
        String url = null;
        File file = new File(excelPath);
        try {
            url = openstorage.uploadFileNew(new FileInputStream(file),
                    "talkres", "feedback", "产品参数管理" + file.getName());
        } catch (FileNotFoundException e) {
            log.error("upload excel file error:" + e.getMessage());
        }
        return CommonResult.Success(url);
    }

    public static void setDynamicScores(Object item, List<FeedbackProductParamScore> feedbackProductParamScores) throws IllegalAccessException, NoSuchFieldException {
        int size = feedbackProductParamScores.size();
        for (int i = 0; i < size && i < 30; i++) { // 确保不超过 score30
            String fieldName = "score" + (i);
            Field field = item.getClass().getDeclaredField(fieldName);
            field.setAccessible(true); // 允许访问私有字段
            FeedbackProductParamScore scoreItem = feedbackProductParamScores.get(i);
            field.set(item, scoreItem.getScore());
        }
    }

    /**
     * @param
     * @Auther: doubaolin
     * @Date: 2024/12/25 10:43
     * @Description: 导入模板
     * @return:
     */
    @Override
    public List<ParamImportVO> importTemp() {
        List<ParamImportVO> res = new ArrayList<>();
        List<OptionVO> optionVOS = feedbackProductParamManagerMapper.tableTitle();
        List<FeedbackProductParamManagerDetail> feedbackProductParamManagerDetails = feedbackProductParamManagerMapper.tableParam();
        feedbackProductParamManagerDetails.stream().forEach(item -> {
            ParamImportVO param = new ParamImportVO();
            param.setCategory(optionVOS.stream().filter(item1 -> item1.getId().equals(item.getParentid())).findFirst().get().getName());
            param.setParamname(item.getParamname());
            res.add(param);
        });
        return res;
    }

    @Override
    public AjaxResult importData(FeedbackProductParamManager feedbackProductParamManager) {
        Map<String, Object> map = this.tableParam();
        String firstTab = map.get("first").toString();
        map.remove("first");
        ObjectMapper objectMapper = new ObjectMapper();
        List<FeedbackProductParamManagerDetail> detailList = new ArrayList<>();
        feedbackProductParamManager.getParameters().forEach((key, value) -> {
            List<FeedbackProductParamManagerDetail> list = objectMapper.convertValue(value,
                    new TypeReference<List<FeedbackProductParamManagerDetail>>() {
                    });
            list.forEach(item1 -> {
                detailList.add(item1);
            });
        });
        detailList.stream().forEach(item -> {
            map.forEach((key, value) -> {
                List<FeedbackProductParamManagerDetail> list = objectMapper.convertValue(value,
                        new TypeReference<List<FeedbackProductParamManagerDetail>>() {
                        });
                list.forEach(item1 -> {
                    if (item1.getParamname().equals(item.getParamname())) {
                        item1.setScore(StringUtils.isNotEmpty(item.getScore())?item.getScore():"");
                        item1.setDetaildescription(StringUtils.isNotEmpty(item.getDetaildescription())?item.getDetaildescription():"");
                    }
                });
                map.put(key, list);
            });
        });
        List<FeedbackProductParamManagerDetail> firstList = objectMapper.convertValue(map.get(firstTab),
                new TypeReference<List<FeedbackProductParamManagerDetail>>() {
                });
        feedbackProductParamManager.setScore(calculateWeightedScore(firstList));
        feedbackProductParamManager.setParameters(map);
        return AjaxResult.success(feedbackProductParamManager);
    }

    @Override
    public List<OptionVO> compareSelectList(String type, String id) {
        List<FeedbackProductParamManager> list = feedbackProductParamManagerMapper.list();
        List<OptionVO> brandlist = feedbackProductVersionManagerMapper.selectProductBrandOption();//产品品牌
        List<OptionVO> typelist = feedbackProductVersionManagerMapper.selectProductTypeOption();//产品品类
        List<OptionVO> modellist = feedbackProductVersionManagerMapper.selectProductModelOption();//产品型号
        List<OptionVO> result = new ArrayList<>();
        if ("1".equals(type)) {
            list.forEach(item -> {
                OptionVO optionVO = new OptionVO();
                optionVO.setId(item.getProductbrandid());
                optionVO.setName(brandlist.stream().filter(item1 -> item1.getId().equals(item.getProductbrandid())).findFirst().get().getName());
                result.add(optionVO);
            });
        }
        if ("2".equals(type)) {
            list.stream().filter(item -> item.getProductbrandid().equals(id)).forEach(item -> {
                OptionVO optionVO = new OptionVO();
                optionVO.setId(item.getProducttypeid());
                optionVO.setName(typelist.stream().filter(item1 -> item1.getId().equals(item.getProducttypeid())).findFirst().get().getName());
                result.add(optionVO);
            });
        }
        if ("3".equals(type)) {
            list.stream().filter(item -> item.getProducttypeid().equals(id)).forEach(item -> {
                OptionVO optionVO = new OptionVO();
                optionVO.setId(item.getProductmodelid());
                optionVO.setName(modellist.stream().filter(item1 -> item1.getId().equals(item.getProductmodelid())).findFirst().get().getName());
                result.add(optionVO);
            });
        }
        if ("4".equals(type)) {
            list.stream().filter(item -> item.getProductmodelid().equals(id)).forEach(item -> {
                OptionVO optionVO = new OptionVO();
                optionVO.setId(item.getId());
                optionVO.setName(item.getModelversion());
                result.add(optionVO);
            });
        }
        return result;
    }

    @Override
    public AjaxResult compareQueryList(FeedbackCompareParams params) {
        Map res = new HashMap();
        List<FeedbackProductParamManager> feedbackProductParamManagers = feedbackProductParamManagerMapper.listCompare(params);
        List<FeedbackProductParamScore> feedbackProductParamScores = feedbackProductParamScoreMapper.selectFeedbackProductParamScoreList();
        List<OptionVO> brandlist = feedbackProductVersionManagerMapper.selectProductBrandOption();//产品品牌
        List<OptionVO> typelist = feedbackProductVersionManagerMapper.selectProductTypeOption();//产品品类
        List<OptionVO> modellist = feedbackProductVersionManagerMapper.selectProductModelOption();//产品型号
        List<echartsVO> echartsList = new ArrayList<>();
        final Integer[] i = {0};
        List<String> colorArr = new ArrayList<>();
        colorArr.add("#5B8FF9");
        colorArr.add("#F6BD16");
        colorArr.add("#FFF000");
        colorArr.add("#FFEFD5");
        colorArr.add("#0000CD");
        colorArr.add("#FFB6C1");
        colorArr.add("#FFFACD");
        colorArr.add("#0000FF");
        feedbackProductParamManagers.forEach(item -> {
            item.setScoreList(feedbackProductParamScores.stream().filter(item1 -> item1.getParentid().equals(item.getId()))
                    .peek(item2 -> {
                        double score = Double.parseDouble(item2.getScore());
                        DecimalFormat df = new DecimalFormat(score == 0 ? "0" : "#.0");
                        String formattedScore = df.format(score);
                        item2.setScore(formattedScore);
                    }).collect(Collectors.toList()));
            item.setProductbrandname(brandlist.stream().filter(item1 -> item1.getId().equals(item.getProductbrandid())).findFirst().get().getName());
            item.setProducttypename(typelist.stream().filter(item1 -> item1.getId().equals(item.getProducttypeid())).findFirst().get().getName());
            item.setProductmodelname(modellist.stream().filter(item1 -> item1.getId().equals(item.getProductmodelid())).findFirst().get().getName());
            List<String> collect = feedbackProductParamScores.stream().filter(item2 -> item2.getParentid().equals(item.getId())).
                    map(item2 -> {
                        double score = Double.parseDouble(item2.getScore());
                        DecimalFormat df = new DecimalFormat(score == 0 ? "0" : "#.0");
                        return df.format(score); // 直接返回格式化后的字符串
                    })
                    .collect(Collectors.toList());
            echartsVO echartsVO = new echartsVO();
            echartsVO.setName(item.getProductmodelname() + "-" + item.getModelversion());
            echartsVO.setValue(collect);
            int colorIndex = i[0] % colorArr.size();
            echartsVO.setColor(colorArr.get(colorIndex));
            echartsList.add(echartsVO);
            i[0]++;
        });
        res.put("list", feedbackProductParamManagers);
        List<legendVO> legendList = new ArrayList<>();
        feedbackProductParamManagerMapper.tableTitle().stream().forEach(item -> {
            legendVO legendVO = new legendVO();
            legendVO.setName(item.getName());
            legendVO.setId(item.getId());
            legendVO.setMax(5);
            legendList.add(legendVO);
        });
        res.put("title", legendList);
        res.put("param", echartsList);
        return AjaxResult.success(res);
    }

    @Override
    public AjaxResult compareQueryListDetail(FeedbackCompareParams params) {
        Map res = new HashMap();
        List<FeedbackProductParamManager> feedbackProductParamManagers = feedbackProductParamManagerMapper.listCompare(params);
        List<String> threeParam = params.getThreeParam()==null?new ArrayList<>():params.getThreeParam();
        List<FeedbackProductParamManagerDetail> detailList = feedbackProductParamManagerDetailMapper.list(threeParam);
        List<OptionVO> brandlist = feedbackProductVersionManagerMapper.selectProductBrandOption();//产品品牌
        List<OptionVO> typelist = feedbackProductVersionManagerMapper.selectProductTypeOption();//产品品类
        List<OptionVO> modellist = feedbackProductVersionManagerMapper.selectProductModelOption();//产品型号
        List<OptionVO> optionVOS = feedbackProductParamManagerMapper.tableTitle();
        List<echartsVO> echartsList = new ArrayList<>();
        final Integer[] i = {0};
        List<String> colorArr = new ArrayList<>();
        colorArr.add("#5B8FF9");
        colorArr.add("#F6BD16");
        colorArr.add("#FFF000");
        colorArr.add("#FFEFD5");
        colorArr.add("#0000CD");
        colorArr.add("#FFB6C1");
        colorArr.add("#FFFACD");
        colorArr.add("#0000FF");
        feedbackProductParamManagers.forEach(item -> {
            item.setParamname(optionVOS.stream().filter(item1 -> item1.getId().equals(params.getParamid())).findFirst().get().getName());
            item.setDetailList(detailList.stream().filter(item1 -> item1.getParentid().equals(item.getId()) && item1.getTypeid().equals(params.getParamid())).collect(Collectors.toList()));
            item.setProductbrandname(brandlist.stream().filter(item1 -> item1.getId().equals(item.getProductbrandid())).findFirst().get().getName());
            item.setProducttypename(typelist.stream().filter(item1 -> item1.getId().equals(item.getProducttypeid())).findFirst().get().getName());
            item.setProductmodelname(modellist.stream().filter(item1 -> item1.getId().equals(item.getProductmodelid())).findFirst().get().getName());
            List<String> collect = detailList.stream().filter(item2 -> item2.getParentid().equals(item.getId()) && item2.getTypeid().equals(params.getParamid()))
                    .map(item2 -> {
                        double score = Double.parseDouble(item2.getScore());
                        DecimalFormat df = new DecimalFormat(score == 0 ? "0" : "#.0");
                        return df.format(score); // 直接返回格式化后的字符串
                    })
                    .collect(Collectors.toList());
            echartsVO echartsVO = new echartsVO();
            echartsVO.setName(item.getProductmodelname() + "-" + item.getModelversion());
            echartsVO.setValue(collect);
            int colorIndex = i[0] % colorArr.size();
            echartsVO.setColor(colorArr.get(colorIndex));
            echartsList.add(echartsVO);
            i[0]++;
        });
        res.put("list", feedbackProductParamManagers);
        List<legendVO> legendList = new ArrayList<>();
        if(threeParam.size()==0){
            feedbackProductParamManagerMapper.tableTitleDetail().stream().filter(item -> item.getId().equals(params.getParamid())).forEach(item -> {
                legendVO legendVO = new legendVO();
                legendVO.setId(item.getId());
                legendVO.setName(item.getName());
                legendVO.setMax(5);
                legendVO.setTrueid(item.getTrueid());
                legendList.add(legendVO);
            });
        }else{
            feedbackProductParamManagerMapper.tableTitleDetail().stream().filter(item -> item.getId().equals(params.getParamid())&&threeParam.contains(item.getName())).forEach(item -> {
                legendVO legendVO = new legendVO();
                legendVO.setId(item.getId());
                legendVO.setName(item.getName());
                legendVO.setTrueid(item.getTrueid());
                legendVO.setMax(5);
                legendList.add(legendVO);
            });
        }
        res.put("title", legendList);
        res.put("param", echartsList);

        return AjaxResult.success(res);
    }

    @Override
    public AjaxResult compareQueryListDetailTable(FeedbackCompareParams params) {
        List<FeedbackProductParamManagerTable> feedbackProductParamManagers = feedbackProductParamManagerMapper.listCompare2(params);
        List<FeedbackProductParamManagerDetail> detailList = feedbackProductParamManagerDetailMapper.list();
        List<OptionVO> brandlist = feedbackProductVersionManagerMapper.selectProductBrandOption();//产品品牌
        List<OptionVO> typelist = feedbackProductVersionManagerMapper.selectProductTypeOption();//产品品类
        List<OptionVO> modellist = feedbackProductVersionManagerMapper.selectProductModelOption();//产品型号
        feedbackProductParamManagers.stream().forEach(item -> {
            item.setProductbrandname(brandlist.stream().filter(item1 -> item1.getId().equals(item.getProductbrandid())).findFirst().get().getName());
            item.setProducttypename(typelist.stream().filter(item1 -> item1.getId().equals(item.getProducttypeid())).findFirst().get().getName());
            item.setProductmodelname(modellist.stream().filter(item1 -> item1.getId().equals(item.getProductmodelid())).findFirst().get().getName());
            Optional<FeedbackProductParamManagerDetail> first = detailList.stream().filter(item1 -> item1.getParentid().equals(item.getId()) && item1.getParamname().equals(params.getParamid())).findFirst();
            item.setScore(first.map(FeedbackProductParamManagerDetail::getScore).orElse(""));
            ParametersVO parametersVO = new ParametersVO();
            String fileUrl = first.map(FeedbackProductParamManagerDetail::getFileurl).orElse("");
            if (StringUtils.isNotEmpty(fileUrl)) {
                parametersVO.setAttachments(Collections.singletonList(
                        new AttachmentsVO(FileUrlUtils.getFileType(fileUrl), fileUrl, FileUrlUtils.getFileNameFromUrl(fileUrl))));
            }

            parametersVO.setDescription(first.map(FeedbackProductParamManagerDetail::getDetaildescription).orElse(""));
            item.setParameters(parametersVO);
        });
        return AjaxResult.success(feedbackProductParamManagers);
    }

    @Override
    public AjaxResult paramList() {
        return AjaxResult.success(feedbackProductParamManagerMapper.tableTitle());
    }
}
